package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    //添加好友
    public void contacts(Long userId) {
        String username1 = "hx" + userId;
        String username2 = "hx" + UserHolder.getUserId();
        //1.将还有注册到环信当中
        huanXinTemplate.addContact(username1, username2);
        //2.将好友写到MongoDb中，操作Friend表
        friendApi.save(UserHolder.getUserId(),userId);
    }

    //查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        //1.获取当前用户id
        Long userId = UserHolder.getUserId();
        //2.根据用户id查询好友表
        List<Friend> friends=friendApi.findFriends(userId,page,pagesize);
        //3.判断一个返回的集合是否为空
        if (CollUtil.isEmpty(friends)){
            return  new PageResult();
        }
        //4.如果不为空就构建返回对象
            //获取到Friend集合当中的所有好友id
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        //根据全部的id的到全部的好友信息
        Map<Long, UserInfo> userInfo = userInfoApi.findByIds(friendIds);
        //构建一个空的返回集合
        List<ContactVo> vos=new ArrayList<>();
        for (Friend friend : friends) {
            //得到好友的id
            Long friendId = friend.getFriendId();
            //在userInfo中查询好友信息
            UserInfo info = userInfo.get(friendId);
            //构建vo对象
            ContactVo vo = ContactVo.init(info);
            vos.add(vo);
        }
        //返回结果
        return new PageResult(page,pagesize,0l,vos);
    }
}
